<?php

namespace App\Library\Address;

use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

/**
 * 高德省市区
 */
class AutoNaviProvinceCityArea
{
    public function __construct()
    {
        $this->initProvinceCityArea();
    }

    public static function getInstance(): self
    {
        return Cache::store('array')->remember("AutoNaviProvinceCityAreaInstance", 300, function () {
            return new self();
        });
    }

    private array $provinceCityArea;

    /**
     * 初始化高德信息
     */
    private function initProvinceCityArea()
    {
        $this->provinceCityArea = WangGuiCityByPower::getChinaDistrict();
    }

    /**
     * 获取全量高德省市区信息
     * @return array
     */
    public function getProvinceCityArea(): array
    {
        return $this->provinceCityArea;
    }
    /**
     * 通过省市区，获取对应编码
     *
     * 允许的参数：
     * 1. 省市区
     * 2. 省市
     * 3. 省
     * @param string $province
     * @param string $city
     * @param string $area
     * @return int[]
     */
    public function getCodesByNames(string $province, string $city, string $area): array
    {
        if (Str::endsWith($province, '市')) {
            $city = mb_substr($province, 0, -1) . '城区';
        }

        $provinceCode = $cityCode = $areaCode = 0;

        foreach ($this->provinceCityArea as $tempProvince) {

            if ($tempProvince['name'] != $province) {
                continue;
            }

            // 省
            $provinceCode = $tempProvince['adcode'];

            foreach ($tempProvince['districts'] as $tempCity) {

                if ($tempCity['name'] != $city) {
                    continue;
                }

                // 市
                $cityCode = $tempCity['adcode'];

                foreach ($tempCity['districts'] as $tempArea) {

                    if ($tempArea['name'] != $area) {
                        continue;
                    }

                    // 区
                    $areaCode = $tempArea['adcode'];
                }
            }
        }

        return [(int)$provinceCode, (int)$cityCode, (int)$areaCode];
    }

    /**
     * 通过cityCode获取省区信息
     * @param int $cityCode
     * @return array
     */
    public function getProvinceByCityCode(int $cityCode): array
    {
        $p = [];

        foreach ($this->provinceCityArea as $tempProvince) {
            foreach ($tempProvince['districts'] as $tempCity) {

                if ($tempCity['adcode'] == $cityCode) {
                    $p = [
                        'code' => $tempProvince['adcode'],
                        'name' => $tempProvince['name'],
                    ];
                }
            }
        }

        return $p;
    }
}
